package com.sanq.product.books.service.impl;

import com.sanq.product.books.config.Redis;
import com.sanq.product.books.entity.vo.BlockVo;
import com.sanq.product.books.mapper.BlockMapper;
import com.sanq.product.books.service.BlockService;
import com.sanq.product.config.utils.entity.Pager;
import com.sanq.product.config.utils.entity.Pagination;
import com.sanq.product.config.utils.string.StringUtil;
import com.sanq.product.config.utils.web.JsonUtil;
import com.sanq.product.redis.service.JedisPoolService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service("blockService")
public class BlockServiceImpl implements BlockService {

	@Resource
	private BlockMapper blockMapper;
	@Resource
	private JedisPoolService jedisPoolService;
	
	@Override
	public int save(BlockVo blockVo) {
		return blockMapper.save(blockVo);
	}
	
	@Override
	public int delete(BlockVo blockVo) {
		return blockMapper.delete(blockVo);
	}	
	
	@Override
	public int update(BlockVo blockVo, Integer id) {
		BlockVo oldBlockVo = findById(id);
		
		if(null != oldBlockVo && null != blockVo) {
			if(null != blockVo.getId()) {
				oldBlockVo.setId(blockVo.getId());
			}
			if(null != blockVo.getBlockName()) {
				oldBlockVo.setBlockName(blockVo.getBlockName());
			}
			if(null != blockVo.getCreateTime()) {
				oldBlockVo.setCreateTime(blockVo.getCreateTime());
			}
			if (!StringUtil.isEmpty(blockVo.getTypeId())) {
				oldBlockVo.setTypeId(blockVo.getTypeId());
			}
			return blockMapper.update(oldBlockVo);
		}
		return 0;
	}
	
	@Override
	public BlockVo findById(Integer id) {
		String key = Redis.ReplaceKey.getBlockId(id);
		String json = jedisPoolService.get(key);
		BlockVo blockVo;
		if (StringUtil.isEmpty(json)) {
			blockVo = blockMapper.findById(id);
			if(blockVo != null)
				jedisPoolService.set(key, JsonUtil.obj2Json(blockVo));
		} else blockVo = JsonUtil.json2Obj(json, BlockVo.class);
		return blockVo;
	}
	
	@Override
	public List<BlockVo> findList(BlockVo blockVo) {
		return blockMapper.findList(blockVo);
	}
	
	@Override
	public Pager<BlockVo> findListByPage(BlockVo blockVo,Pagination pagination) {
		pagination.setTotalCount(findCount(blockVo));
		
		List<BlockVo> datas = blockMapper.findListByPage(blockVo,pagination.getStartPage(),pagination.getPageSize());
		
		return new Pager<BlockVo>(pagination,datas);
	}
	
	@Override
	public int findCount(BlockVo blockVo) {
		return blockMapper.findCount(blockVo);
	}
	
	@Override
	public void saveByList(List<BlockVo> blockVos) {
		blockMapper.saveByList(blockVos);
	}
}